package org.justframework.plugin.http;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.justframework.api.connector.Request;
import org.justframework.api.connector.Response;
import org.justframework.api.dispatcher.DispatcherFactory;
import org.justframework.core.mapper.MapperFactory;
import org.justframework.util.JsonUtil;
import org.mortbay.jetty.handler.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 
 * http request handler adapter 
 * 
 */
public class HttpHandlerAdapter extends AbstractHandler {
	
	/**
	 * logger
	 */
	private static Logger logger = LoggerFactory.getLogger(HttpHandlerAdapter.class);
	
	public void handle(String target, HttpServletRequest servletRequest,
			HttpServletResponse servletResponse, int dispatch) throws IOException,
			ServletException {
		try{
			//create and fill request
			Request request = createJustRequest(target, servletRequest);
			logger.debug("request obj:{}",request);
			//create response
			Response response = new Response();
			//handler request
			DispatcherFactory.getDefaultDispatcher().dispatch(request, response, null);
			logger.debug("response obj:{}",response);
			//convert response to json string
			String result = MapperFactory.getDefaultMapper().toSerial(response);
			//reply to client 
			servletResponse.setContentType(request.getRepresentType());
			servletResponse.getWriter().write(result);
			servletResponse.flushBuffer();
			
			((org.mortbay.jetty.Request) servletRequest).setHandled(true);
		}catch(Exception e){
			logger.error("HttpHandlerAdapter error",e);
			servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}
	
	/**
	 * get request instance by parsing package json request
	 * @param target
	 * @param servletRequest
	 * @return
	 */
	private Request createJustRequest(String target, HttpServletRequest servletRequest){
		String requestJson = servletRequest.getParameter("_jt_request");
		logger.debug("HttpHandlerAdapter requestJson:{}",requestJson);
		if(requestJson != null){
			return MapperFactory.getDefaultMapper().toBean(requestJson, Request.class);
		}
		return null;
	}
	
}
